package com.zzti.pay.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadFile {
	// url文件的绝对路径
	public static void downloadFile(String url, String name, HttpServletRequest request, HttpServletResponse response) {
		// String webpath =
		// request.getSession().getServletContext().getRealPath("") +
		// File.separator + "upload/";
		// 取得文件的文件名加后缀名。
		// String name = url.substring(url.lastIndexOf("/")
		// ,url.lastIndexOf(""));
		// 文件的绝对路径(斜杠截取会出现乱码暂且不用)
		try {
			execute(request, response, url, name);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void execute(HttpServletRequest request, HttpServletResponse response, String fileAbsPath,
			String showName) throws Exception {
		execute(request, response, new File(fileAbsPath), showName);
	}

	public static void execute(HttpServletRequest request, HttpServletResponse response, File file, String showName)
			throws Exception {
		execute(request, response, new FileInputStream(file), file.length(), showName);
	}

	public static void execute(HttpServletRequest request, HttpServletResponse response, InputStream input, long length,
			String showName) throws Exception {
		String info = request.getHeader("User-Agent").toLowerCase();
		if (info.contains("firefox")) { // Firefox
			showName = new String(showName.getBytes(), "ISO-8859-1");
		} else { // IE,Chrome
			showName = URLEncoder.encode(showName, "UTF-8");
		}

		response.reset(); // 响应重置
		response.setHeader("Content-Disposition", "attachment; filename=\"" + showName + "\"");
		// response.addHeader("Content-Length", ""+length);
		response.setContentType("application/octet-stream;charset=UTF-8");
		OutputStream out = response.getOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024 * 8];
		while ((len = input.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		input.close();
		out.close();
		response.flushBuffer();
	}

	// 网络文件下载到浏览器中
	public static void downloadToExplorerFormUrl(String urlStr, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 从url中截取文件后缀名
		String fileSuffix = urlStr.substring(urlStr.lastIndexOf("."), urlStr.lastIndexOf(""));
		// 重命名文件
		String showName = System.currentTimeMillis() + "." + fileSuffix;

		String info = request.getHeader("User-Agent").toLowerCase();
		if (info.contains("firefox")) { // Firefox
			showName = new String(showName.getBytes(), "ISO-8859-1");
		} else { // IE,Chrome
			showName = URLEncoder.encode(showName, "UTF-8");
		}

		response.reset(); // 响应重置
		response.setHeader("Content-Disposition", "attachment; filename=\"" + showName + "\"");// 告诉浏览器要下载的文件的名字
		// 以二进制流的形式下载
		response.setContentType("application/octet-stream;charset=UTF-8");
		OutputStream out = response.getOutputStream();
		// 这里开始读取要下载的文件
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(3 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		// 得到输入流
		InputStream inputStream = conn.getInputStream();
		int len = 0;
		byte[] buffer = new byte[1024 * 8];
		while ((len = inputStream.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		inputStream.close();
		out.close();
		response.flushBuffer();
	}

	// 网络文件下载
	public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(3 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		// 得到输入流
		InputStream inputStream = conn.getInputStream();
		// 获取自己数组
		byte[] getData = readInputStream(inputStream);

		// 文件保存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		File file = new File(saveDir + File.separator + fileName);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(getData);
		if (fos != null) {
			fos.close();
		}
		if (inputStream != null) {
			inputStream.close();
		}

		System.out.println("info:" + url + " download success");

	}

	/**
	 * 从输入流中获取字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

}
